/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import dao.ClienteDAO;
import dao.FabricanteDAO;
import dao.PedidoDAO;
import entity.Cliente;
import entity.Fabricante;
import entity.Pedido;
import entity.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Tiago
 */
@WebServlet(name = "ControladoraPedido", urlPatterns = {"/ControladoraPedido"})
public class ControladoraPedido extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet teste</title>");        
        out.println("</head>");
        out.println("<body>");        
        
        String action = request.getParameter("action");
        
        if (action.equals("inserir")) {
            
            out.println("aqui");
            SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            String tipoProd = request.getParameter("campoTipo");
            String cli = request.getParameter("cliente");
            String modelo = request.getParameter("campoModelo");
            String desc = request.getParameter("campoDescricao");
            String fabricante = request.getParameter("campoFabricante");
            Double valor = Double.parseDouble(request.getParameter("campoValor"));            
            Date dt_entrada = new Date(df.parse(request.getParameter("campoDataEntrada")).getTime());
            Date dt_prevista = new Date(df.parse(request.getParameter("campoDataPrevista")).getTime());            
            
            HttpSession session = request.getSession();            
            Usuario user = (Usuario) session.getAttribute("user");
            
            Pedido pedido = new Pedido();
            pedido.setTipoProduto(tipoProd);
            pedido.setModelo(modelo);
            pedido.setDescProblema(desc);
            pedido.setValor(valor);
            pedido.setDataEntrada(dt_entrada);
            pedido.setDataPrevista(dt_prevista);
            pedido.setIdFabricante(Integer.parseInt(fabricante));
            pedido.setIdCliente(Integer.parseInt(cli));
            PedidoDAO pdao = new PedidoDAO();
            
            pdao.insere(pedido);
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/pedido_aberto.jsp");
            rd.forward(request, response);;
        } else if (action.equals("visualizar")) {
            int idPedido = Integer.parseInt(request.getParameter("idpedido"));
            out.println("aqui");
            
            Pedido pedido = new Pedido();
            PedidoDAO daopedido = new PedidoDAO();
            ClienteDAO nomeClienteDAO = new ClienteDAO();
            Cliente cliente = new Cliente();
            Fabricante fabricante = new Fabricante();
            FabricanteDAO fabricanteDAO = new FabricanteDAO();
            
            pedido = daopedido.getPedido(idPedido);
            fabricante = fabricanteDAO.buscaFab(pedido.getIdFabricante());
            pedido.setNomeFabricante(fabricante.getNome());
            cliente = nomeClienteDAO.buscaCli(pedido.getIdCliente());
            pedido.setNomeCliente(cliente.getNome());            
            request.setAttribute("pedido", pedido);
            
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/detalhes_pedido.jsp");
            rd.forward(request, response);            
        } else if (action.equals("pesquisar")) {
            String pesquisa = request.getParameter("campoPesquisa");
            
            PedidoDAO pedidoDAO = new PedidoDAO();
            List<Pedido> pedidos = new ArrayList();
            
            pedidos.addAll(pedidoDAO.procurar(pesquisa));
            out.println("aqui");
            request.setAttribute("pedidos", pedidos);
           
           // response.sendRedirect("teste");
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/pesquisar_pedido.jsp");
            rd.forward(request, response);            
            
        } else if(action.equals("pesquisar")){
            String pesquisa = request.getParameter("campoPesquisa");
            
            PedidoDAO pedidoDAO = new PedidoDAO();
            List<Pedido> pedidos = new ArrayList();
            out.println(pesquisa);
            pedidos.addAll(pedidoDAO.buscar(pesquisa));
            out.println("aqui");
            request.setAttribute("pedidos", pedidos);
            
           // response.sendRedirect("teste");
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/pesquisar_pedido.jsp");
            rd.forward(request, response);            

        }
        out.println("aqui");
        
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(ControladoraPedido.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ControladoraPedido.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(ControladoraPedido.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ControladoraPedido.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
